package 链表题.合并多个有序链表;

import 链表题.ListNode;

/**
 * 递归调用
 */

public class Test1 {
    private static ListNode mergeTwoLists(ListNode p1, ListNode p2) {
        ListNode s = new ListNode(-1, null);
        ListNode p = s;
        while (p1 != null && p2 != null) {
            if (p1.val < p2.val) {
                p.next = p1;
                p = p.next;
                p1 = p1.next;
            } else {
                p.next = p2;
                p = p.next;
                p2 = p2.next;
            }
        }
        p.next = p1 == null ? p2 : p1;
        return s.next;
    }

    public static ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        int i = 0;
        int j = lists.length - 1;
        return split(lists, i, j);
    }

    private static ListNode split(ListNode[] lists, int i, int j) {
        if (i == j) {
            return lists[i];
        }
        int m = (i + j) >>> 1;
        ListNode left = split(lists, i, m);
        ListNode right = split(lists, m + 1, j);
        return mergeTwoLists(left, right);
    }



    public static void main(String[] args) {
        ListNode[] lists = {ListNode.of(1, 5, 8), ListNode.of(2, 3, 10), ListNode.of(4, 6, 7, 9)};
        for (ListNode list : lists) {
            System.out.println(list);
        }
        System.out.println(mergeKLists(lists));
    }
}
